package com.huatai.bi.config;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.List;

/**
 * @program: ht-system
 * @description: redisson配置
 * @author: hecaiy
 * @create: 2023-02-10 10:31
 **/
@Configuration
public class RedissonConfig {

	@Autowired
	private RedisProperties redisProperties;

	@Autowired
	private Environment environment;

	@Bean
	public RedissonClient redissonClient() {
		Config config = new Config();

		String password = redisProperties.getPassword();

		if(null != redisProperties.getCluster()){//集群
			ClusterServersConfig serversConfig = config.useClusterServers();
			RedisProperties.Cluster cluster = redisProperties.getCluster();
			for (String node : cluster.getNodes()){
				serversConfig.addNodeAddress("redis://"+node);
			}
			serversConfig.addNodeAddress();
			if (StringUtils.isNotBlank(password)) {
				serversConfig.setPassword(password);
			}

		} else if (null != redisProperties.getSentinel()) {//哨兵
			SentinelServersConfig serversConfig = config.useSentinelServers();
			RedisProperties.Sentinel sentinel = redisProperties.getSentinel();
			List<String> nodes = sentinel.getNodes();
			for (String node : nodes) {
				serversConfig.addSentinelAddress("redis://"+node);
			}
			serversConfig.setMasterName(sentinel.getMaster());
			serversConfig.setDatabase(redisProperties.getDatabase());
			if (StringUtils.isNotBlank(password)) {
				serversConfig.setPassword(password);
			}
		}else{

			String nodes = environment.getProperty("spring.redis.slave.nodes");
			String redisUrl = String.format("redis://%s:%s", redisProperties.getHost() + "", redisProperties.getPort() + "");
			if(null == nodes){//单机
				SingleServerConfig serversConfig = config.useSingleServer();
				serversConfig.setAddress(redisUrl);
				if(StringUtils.isNotEmpty(password)){
					serversConfig.setPassword(password);
				}
				serversConfig.setDatabase(redisProperties.getDatabase());
			}else{//主从
				MasterSlaveServersConfig serversConfig = config.useMasterSlaveServers();
				serversConfig.setMasterAddress(redisUrl);

				String[] nodeArray = nodes.split(",");
				for (String node : nodeArray) {
					serversConfig.addSlaveAddress("redis://"+node);
				}

				if(StringUtils.isNotEmpty(password)){
					serversConfig.setPassword(password);
				}
				serversConfig.setDatabase(redisProperties.getDatabase());
			}
		}
		config.setCodec(new JsonJacksonCodec());
		return Redisson.create(config);
	}

}
